<!DOCTYPE html>
<html lang="en">
  <head>
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
    />
    <style>
      html {
        width: 100%;
        height: 100%;
        background-color: black;
        pointer-events: <<pointerEvents>>;
      }

      body {
        margin: 0;
        width: 100%;
        height: 100%;
        background-color: black;
        pointer-events: inherit;
      }

      .embed-container iframe,
      .embed-container object,
      .embed-container embed {
        position: absolute;
        top: 0;
        left: 0;
        width: 100% !important;
        height: 100% !important;
        pointer-events: inherit;
      }
    </style>
    <title>Youtube Player</title>
  </head>

  <body>
    <div class="embed-container">
      <div id="<<playerId>>"></div>
    </div>

    <script>
      var tag = document.createElement("script");
      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName("script")[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

      var platform = "<<platform>>";
      var host = "<<host>>";
      var player;
      var timerId;

      function onYouTubeIframeAPIReady() {
        player = new YT.Player("<<playerId>>", {
          host: host,
          playerVars: <<playerVars>>,
          events: {
            onReady: function (event) {
              handleFullScreenForMobilePlatform();
              sendMessage('Ready', event);
            },
            onStateChange: function (event) {
              clearTimeout(timerId);
              sendMessage('StateChange', event.data);
              if (event.data == 1) {
                timerId = setInterval(function () {
                  var state = {
                    'currentTime': player.getCurrentTime(),
                    'loadedFraction': player.getVideoLoadedFraction()
                  };

                  sendMessage('VideoState', JSON.stringify(state));
                }, 100);
              }
            },
            onPlaybackQualityChange: function (event) {
              sendMessage('PlaybackQualityChange', event.data);
            },
            onPlaybackRateChange: function (event) {
              sendMessage('PlaybackRateChange', event.data);
            },
            onApiChange: function (event) {
              sendMessage('ApiChange', event.data);
            },
            onError: function (event) {
              sendMessage('PlayerError', event.data);
            },
            onAutoplayBlocked: function (event) {
              sendMessage('AutoplayBlocked', event.data);
            },
          },
        });
        player.setSize(window.innerWidth, window.innerHeight);
      }

      window.addEventListener('message', (event) => {
        try {
          var data = JSON.parse(event.data);

          if(data.function){
            var rawFunction = data.function.replaceAll('<<quote>>', '"');
            var result = eval(rawFunction);

            if(data.key) {
              var message = {}
              message[data.key] = result
              var messageString = JSON.stringify(message);

              event.source.postMessage(messageString , '*');
            }
          }
        } catch (e) { }
      }, false);

      window.onresize = function () {
        player.setSize(window.innerWidth, window.innerHeight);
      };

      function sendPlatformMessage(message) {
        switch(platform) {
           case 'android':
             <<playerId>>.postMessage(message);
             break;
           case 'ios':
             <<playerId>>.postMessage(message, '*');
             break;
           case 'web':
             window.parent.postMessage(message, '*');
             break;
         }
      }

      function sendMessage(key, data) {
         var message = {};
         message[key] = data;
         message['playerId'] = '<<playerId>>';
         var messageString = JSON.stringify(message);

         sendPlatformMessage(messageString);
      }

      function getVideoData() {
        return prepareDataForPlatform(player.getVideoData());
      }

      function getPlaylist() {
        return prepareDataForPlatform(player.getPlaylist());
      }

      function getAvailablePlaybackRates(){
        return prepareDataForPlatform(player.getAvailablePlaybackRates());
      }

      function prepareDataForPlatform(data) {
        if(platform == 'android') return data;

        return JSON.stringify(data);
      }

      function handleFullScreenForMobilePlatform() {
        if(platform != 'web') {
          var ytFrame = document.getElementsByTagName('iframe')[0].contentWindow.document;
          var fsButton = ytFrame.getElementsByClassName('ytp-fullscreen-button ytp-button')[0];

          if(fsButton != null) {
            var fsButtonCopy = fsButton.cloneNode(true);
            fsButton.replaceWith(fsButtonCopy);
            fsButtonCopy.onclick = function() {
              sendMessage('FullscreenButtonPressed', '');
            };
          }
        }
      }
    </script>
  </body>
</html>
